﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Xml;
using System.Text;
using xrwang.weixin.PublicAccount;

public partial class Test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string userName = /*"gh_9272e54e91d3"*/"gh_5dbae931ec49";
        ErrorMessage errorMessage;
        DateTime now = DateTime.Now;
        ltrTime.Text = now.ToString();
        ltrMsg.Text = TimeZoneInfo.ConvertTimeToUtc(now).ToString() + string.Format("{0}", null ?? "");
        //AccessToken token=AccessToken.Get(userName);
        //ltrAccessToken.Text = token != null ? token.access_token : string.Empty;
        //string xml = @"<xml><URL><![CDATA[http://www.xrwang.net/WeixinInterface.ashx]]></URL><ToUserName><![CDATA[gh_9272e54e91d3]]></ToUserName><FromUserName><![CDATA[oFD0Qs5AvzmW3xqnXATe-BLePrck]]></FromUserName><CreateTime>123455</CreateTime><MsgType><![CDATA[event]]></MsgType><Event><![CDATA[location]]></Event><Latitude>123</Latitude><Longitude>345</Longitude><Precision>10</Precision><MsgId>123455</MsgId></xml>";
        //RequestBaseMessage msg = RequestMessageHelper.Parse(xml);
        //errorMessage = CreateMenu(userName);
        //ltrMenu.Text = errorMessage.IsSuccess ? "create menu success" : errorMessage.ToString();
        //ltrMenu.Text = GetMenu(userName);
        //ltrMenu.Text = DeleteMenu(userName) ? "已删除菜单" : "删除菜单失败";
        /*string xml=@"<xml><ToUserName><![CDATA[gh_5dbae931ec49]]></ToUserName>
<FromUserName><![CDATA[ojyxtuImDUYDw1gtvsMHt7ZpxKTI]]></FromUserName>
<CreateTime>1424129073</CreateTime>

<MsgType><![CDATA[event]]></MsgType>

<Event><![CDATA[pic_photo_or_album]]></Event>

<EventKey><![CDATA[photo_or_album]]></EventKey>

<SendPicsInfo>
	<Count>1</Count>
	
<PicList>
		<item><PicMd5Sum><![CDATA[063ab6455f07967cb767f78d6d2e4e25]]></PicMd5Sum>
</item>
	
</PicList>

</SendPicsInfo>

</xml>";
        ltrMenu.Text = ParseRequestMessage(xml);*/
        //QrCode code = QrCode.Create(userName, 1, out errorMessage);
        //ltrMenu.Text = errorMessage.IsSuccess ? code.ToString() : errorMessage.ToString();
        //string url = ShortUrl.Get(userName, "http://www.cnblogs.com/xrwang/", out errorMessage);
        //ltrMenu.Text = errorMessage.IsSuccess ? url : errorMessage.ToString();
        //int groupId = UserManagement.CreateGroup(userName, "同学", out errorMessage);
        //ltrMenu.Text = errorMessage.IsSuccess ? string.Format("已创建的分组id：{0}", groupId) : errorMessage.ToString();
        //ltrMenu.Text = GetGroup(userName);
        //ltrMenu.Text = UserManagement.ChangeGroupName(userName, 100, "同学").ToString();
        //ltrMenu.Text = GetUserList(userName);
        //ltrMenu.Text = GetUserInfo(userName, "ojyxtuImDUYDw1gtvsMHt7ZpxKTI");
        //ltrMenu.Text = UserManagement.ChangeUserRemark(userName, "ojyxtuImDUYDw1gtvsMHt7ZpxKTI", "酷型男").ToString();
        //int groupId = UserManagement.GetGroupId(userName, "ojyxtuImDUYDw1gtvsMHt7ZpxKTI", out errorMessage);
        //ltrMenu.Text = errorMessage.IsSuccess ? groupId.ToString() : errorMessage.ToString();
        //ltrMenu.Text = UserManagement.MoveUser(userName, 100, "ojyxtuImDUYDw1gtvsMHt7ZpxKTI").ToString();
        //ltrMenu.Text = UploadArticle(userName);
        //ltrMenu.Text = SendMassMessage(userName);
        //ltrMenu.Text = PreviewMassMessage(userName,openId);
        //ltrMenu.Text = TemplateMessage.SetIndustry(userName, Industry.SoftwareOrService, Industry.InternetOrElectronicBusiness).ToString();
        //ltrMenu.Text = GetTemplateMessageId(userName);
        //string templateId = "X-x1jaFh5sP4Gx6N9WUG7g6O2HDfBdHY1g0U_nnBL_w";
        //ltrMenu.Text = SendTemplateMessage(userName, openId, "X-x1jaFh5sP4Gx6N9WUG7g6O2HDfBdHY1g0U_nnBL_w");
        //ltrMenu.Text = SendTemplateMessage(userName, openId, "z8zHvTm2gpU0gZUBwA0dXibMO_VYy6iwJYgtW6qeyPg");
        //ltrMenu.Text = OAuthAccessToken.GetOAuthUrl(userName, "http://localhost:19899/Test.aspx", OAuthScopeEnum.snsapi_base, "test");
        //ltrMenu.Text = GetKfList(userName);
        //ltrMenu.Text = "添加客服账号：" + CustomerService.Add(userName, "1@xrwang3128"/* + userName*/, "小猫", "1").ToString();
        //ltrMenu.Text = "删除客服账号：" + CustomerService.Delete(userName, "1@xrwang2").ToString();
        //string tulingKey = "976e1fe2ef32277ab4cee4b296a9114a";
        //xrwang.Tuling.BaseResult result= xrwang.Tuling.Tuling.Request(tulingKey, "iphone6的价格", string.Empty, string.Empty);
        //ltrMenu.Text = result == null ? "图灵服务器错误" : result.ToString();
        //string result = "{\"code\":304000,\"text\":\"********\",\"list\":[{\"name\":\"\",\"count\":\"\",\"detailurl\":\"\",\"icon\":\"\"}]}";
        //ltrMenu.Text = xrwang.Tuling.BaseResult.Parse(result).ToString();
    }

    private ErrorMessage CreateMenu(string userName)
    {
        MenuContainer mc1 = MenuHelper.CreateContainer("酷型男");
        mc1.Add(MenuHelper.CreateItem(MenuTypeEnum.click, "关于", "about"));
        mc1.Add(MenuHelper.CreateItem(MenuTypeEnum.view, "博客", "http://xrwang.cnblogs.com"));
        mc1.Add(MenuHelper.CreateItem(MenuTypeEnum.location_select, "方位", "location"));
        mc1.Add(MenuHelper.CreateItem(MenuTypeEnum.view, "网页授权", OAuthAccessToken.GetOAuthUrl(userName, "http://www.xrwang.net/OAuth.aspx", OAuthScopeEnum.snsapi_userinfo, "oauth")));
        MenuContainer mc2 = MenuHelper.CreateContainer("扫描");
        mc2.Add(MenuHelper.CreateItem(MenuTypeEnum.scancode_push, "扫码推", "push"));
        mc2.Add(MenuHelper.CreateItem(MenuTypeEnum.scancode_waitmsg, "接收扫码", "waitmsg"));
        MenuContainer mc3 = MenuHelper.CreateContainer("发图");
        mc3.Add(MenuHelper.CreateItem(MenuTypeEnum.pic_sysphoto, "系统发图", "sysphoto"));
        mc3.Add(MenuHelper.CreateItem(MenuTypeEnum.pic_photo_or_album, "拍照或相册发图", "photo_or_album"));
        mc3.Add(MenuHelper.CreateItem(MenuTypeEnum.pic_weixin, "微信发图", "weixin"));
        return MenuHelper.Create(userName, new BaseMenu[] { mc1, mc2, mc3 });
    }

    private string GetMenu(string userName)
    {
        ErrorMessage msg;
        BaseMenu[] menus = MenuHelper.Get(userName, out msg);
        StringBuilder sb = new StringBuilder();
        if(menus!=null&&menus.Length>0)
        {
            foreach (BaseMenu menu in menus)
                sb.Append(menu.ToString());
        }
        return sb.ToString();
    }

    private bool DeleteMenu(string userName)
    {
        return MenuHelper.Delete(userName).IsSuccess;
    }

    private string DecryptMessage(string content)
    {
        string msg = "";
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(content);
        string json = JsonConvert.SerializeXmlNode(doc);
        JObject jo = (JObject)JObject.Parse(json)["xml"];
        string userName = (string)jo["ToUserName"]["#cdata-section"];
        AccountInfo account = AccountInfoCollection.GetAccountInfo(userName);
        if (account == null)
            return msg;
        ///WeixinInterface.ashx?signature=88ebb7cf0e978b5e6e2a02e70105b16a35c4b954&timestamp=1424006462&nonce=327332521&encrypt_type=aes&msg_signature=fd08010cf9f217f311e1851a9a0e3425db028a39
        Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(account.Token, account.EncodingAESKey, account.AppId);
        string msg_signature = "32e7f51d806e0845d5d1aedddfa5aefdf887f9ac";
        string timestamp = "1424007723";
        string nonce = "1797852099";
        wxcpt.DecryptMsg(msg_signature, timestamp, nonce, content, ref msg);
        return msg;
    }

    private string ParseRequestMessage(string xml)
    {
        RequestBaseMessage msg = RequestMessageHelper.Parse(xml);
        return msg.ToString();
    }

    private string GetGroup(string userName)
    {
        ErrorMessage errorMessage;
        UserGroup[] groups = UserManagement.GetGroup(userName, out errorMessage);
        if (errorMessage.IsSuccess)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("用户分组数目：{0}\r\n", groups.Length);
            foreach (UserGroup group in groups)
                sb.AppendFormat("{0}\r\n", group);
            return sb.ToString();
        }
        else
           return errorMessage.ToString();
    }

    private string GetUserList(string userName)
    {
        string[] users = UserManagement.GetUserList(userName);
        StringBuilder sb = new StringBuilder();
        sb.AppendFormat("用户数目：{0}\r\n", users != null ? users.Length : 0);
        if (users == null || users.Length == 0)
            sb.Append("获取用户列表失败。");
        else
        {
            sb.Append("用户列表：");
            foreach (string user in users)
                sb.AppendFormat("{0},", user);
        }
        return sb.ToString();
    }

    private string GetUserInfo(string userName,string openId)
    {
        ErrorMessage errorMessage;
        UserInfo info = UserManagement.GetUserInfo(userName, openId, out errorMessage);
        return errorMessage.IsSuccess ? info.nickname + info.unionid : errorMessage.ToString();
    }

    private string UploadArticle(string userName)
    {
        StringBuilder sb = new StringBuilder();
        string filename = Page.MapPath("~/images/picture.jpg");
        //string thumbMediaId = "wXFTZ-hQd9wxjEpeGZVzHN01-V0gs7wnc1LoJdB8Nf4ZZXO8274dRX1mahsHMB6v";
        ErrorMessage errorMessage;
        MultiMediaUploadResult result = MultiMediaHelper.Upload(userName, MultiMediaTypeEnum.image, filename, out errorMessage);
        sb.Append(errorMessage.IsSuccess ? result.MediaId : errorMessage.ToString());
        if(errorMessage.IsSuccess)
        {
            MultiMediaArticle article = new MultiMediaArticle(result.MediaId, "test title", "this is a test.", "xrwang", "http://xrwang.cnblogs.com", "test", true);
            result = MultiMediaHelper.Upload(userName, new MultiMediaArticle[] { article }, out errorMessage);
            //string newsid="0-lZZAsLEwYJXlQrVACz-Ug0Sm6f3ulGh-ywVwDxDT6jzWIQ3bfMFovC8Y730R7n";
            sb.AppendFormat("<br />{0}", errorMessage.IsSuccess ? result.MediaId : errorMessage.ToString());
        }
        return sb.ToString();
    }

    private string SendMassMessage(string userName)
    {
        ErrorMessage errorMessage;
        long id = MassMessage.Send(userName, true, "", MassMessageTypeEnum.mpnews, "0-lZZAsLEwYJXlQrVACz-Ug0Sm6f3ulGh-ywVwDxDT6jzWIQ3bfMFovC8Y730R7n", out errorMessage);
        return errorMessage.IsSuccess ? id.ToString() : errorMessage.ToString();
    }

    private string PreviewMassMessage(string userName,string openId)
    {
        ErrorMessage errorMessage;
        long id = MassMessage.Preview(userName,openId, MassMessageTypeEnum.mpnews, "0-lZZAsLEwYJXlQrVACz-Ug0Sm6f3ulGh-ywVwDxDT6jzWIQ3bfMFovC8Y730R7n", out errorMessage);
        return errorMessage.IsSuccess ? id.ToString() : errorMessage.ToString();
    }

    private string GetTemplateMessageId(string userName)
    {
        ErrorMessage errorMessage;
        string id = TemplateMessage.GetId(userName, "TM00015", out errorMessage);
        return errorMessage.IsSuccess ? id : errorMessage.ToString();
    }

    private string SendTemplateMessage(string userName,string openId,string templateId)
    {
        ErrorMessage errorMessage;
        long id=TemplateMessage.Send(userName,openId,templateId,"http://xrwang.cnblogs.com",System.Drawing.Color.Red,
            new Tuple<string,string,System.Drawing.Color>[]{
                new Tuple<string,string,System.Drawing.Color>("title","新年快乐!",System.Drawing.Color.Pink),
                new Tuple<string,string,System.Drawing.Color>("username",openId,System.Drawing.Color.Black),
                new Tuple<string,string,System.Drawing.Color>("time",DateTime.Now.ToString(),System.Drawing.Color.Blue)
            },out errorMessage);
        return errorMessage.IsSuccess ? string.Format("发送成功：{0}", id) : errorMessage.ToString();
    }

    private string GetKfList(string userName)
    {
        StringBuilder sb = new StringBuilder();
        ErrorMessage errorMessage;
        List<CustomerServiceAccount> accounts = CustomerService.GetKfList(userName, out errorMessage);
        if (errorMessage.IsSuccess)
        {
            sb.Append("获取客服列表成功。");
            if (accounts != null && accounts.Count > 0)
            {
                sb.AppendFormat("客服人数：{0}人。", accounts.Count);
                foreach (CustomerServiceAccount account in accounts)
                    sb.AppendFormat("\r\n{0}", account);
            }
            else
                sb.Append("没有客服。");
        }
        else
            sb.AppendFormat("获取客服失败。{0}", errorMessage);
        return sb.ToString();
    }
}